package tragame.game;

import java.rmi.RemoteException;

import tragame.interfaces.IBuilding;
import tragame.interfaces.IBuildingProd;
import tragame.interfaces.IBuildingStorage;

public class BuildingThread extends Thread{

	private IBuilding building;
	
	public void run() {			
		
		try {
			
			int oldCostFood = building.getCostFood();
			building.setCostFood(oldCostFood * 2);
			
			int oldCostWood = building.getCostWood();
			building.setCostWood(oldCostWood * 2);
			
			int oldCostSoil = building.getCostSoil();
			building.setCostSoil(oldCostSoil * 2);
			
			int oldCostIron = building.getCostIron();
			building.setCostIron(oldCostIron * 2);
			
			int remainingTime = building.getRemainingTime();
			
			while(remainingTime != 0){
				synchronized(this){
					building.setRemainingTime(--remainingTime);					
					Thread.sleep(1000);
					remainingTime = building.getRemainingTime();
				}
			}
			
			int oldConstructionTime = building.getConstructionTime();
			
			building.setConstructionTime(oldConstructionTime * 3);
		
			int oldLevel = building.getLevel();
			building.setLevel(++oldLevel);
		
			building.setStatus(1);
			
			if(building instanceof IBuildingProd)
				if(building.getStatus().equals("Non construit"))
					((IBuildingProd)building).createBuilding();
				else ((IBuildingProd)building).upgradeBuilding();
			else if(building instanceof IBuildingStorage)
				if(building.getStatus().equals("Non construit"))
					((IBuildingStorage)building).createBuilding();
				else ((IBuildingStorage)building).upgradeBuilding();
			else building.constructBuilding();
			
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}		
	}
	
	public void setBuildling(IBuilding building){
		this.building = building;
	}
}
